package io.dy.config;

import io.dy.bean.Bean_01;
import io.dy.bean.Bean_02;
import io.dy.bean.Bean_03;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.GenericApplicationContext;

import java.lang.reflect.Method;

/**
 * @author : dmj
 * @date: 2024/6/3 6:53 下午
 * @description: 手动添加初始化器
 */
//@Configuration
public class Dy_03 {

    public static void main(String[] args) throws Exception {
        //1、创建 SpringApplication
        SpringApplication application = new SpringApplication(Dy_03.class);

        //2、添加初始化器到容器中
        application.addInitializers(new ApplicationContextInitializer<ConfigurableApplicationContext>() {
            @Override
            public void initialize(ConfigurableApplicationContext applicationContext) {
                if (applicationContext instanceof GenericApplicationContext) {
                    //通过初始化器 自定义添加beanDefinition 换句话 就是可以通过初始化器 额外添加bean定义
                    GenericApplicationContext context = (GenericApplicationContext)applicationContext;
                    context.registerBean("bean_03", Bean_03.class);
                }
            }
        });

        //3、run容器
        ConfigurableApplicationContext context = application.run(args);

        //4、查看BeanDefinition 以及 来源
        for (String name : context.getBeanDefinitionNames()) {
            System.out.println("\t 名称:" + name + " 来源:" + context.getBeanFactory().getBeanDefinition(name).getResourceDescription());
        }

        context.close();
    }


    @Bean
    public Bean_01 bean_01(){
        return new Bean_01();
    }

    @Bean
    public Bean_02 bean_02(){
        return new Bean_02();
    }

    @Bean
    public TomcatServletWebServerFactory servletWebServerFactory(){
        return new TomcatServletWebServerFactory();
    }
}
